# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

from django import forms

from crashstats.crashstats.forms import BaseForm


class ExploitabilityReportForm(BaseForm):

    product = forms.ChoiceField()
    version = forms.ChoiceField(required=False)

    def __init__(self, *args, **kwargs):
        active_versions = kwargs.pop('active_versions')
        self.available_products = dict(
            (p, [x['version'] for x in v])
            for p, v in active_versions.items()
        )
        super().__init__(*args, **kwargs)

        self.fields['product'].choices = [
            (k, k) for k in self.available_products
        ]
        all_versions = []
        [all_versions.extend(v) for v in self.available_products.values()]

        self.fields['version'].choices = [
            (v, v) for v in set(
                x for line in self.available_products.values() for x in line
            )
        ]

    def clean(self):
        cleaned_data = super().clean()
        if 'product' in cleaned_data and 'version' in cleaned_data:
            product = cleaned_data['product']
            version = cleaned_data['version']
            if version and version not in self.available_products[product]:
                raise forms.ValidationError(
                    '{} is not an available version for {}'.format(
                        version,
                        product,
                    )
                )
        return cleaned_data
